package cn.tedu.ymg.product.service.impl;

import cn.tedu.ymg.commons.ex.ServiceException;
import cn.tedu.ymg.commons.pojo.vo.PageData;
import cn.tedu.ymg.commons.util.PageInfoToPageDataConverter;
import cn.tedu.ymg.commons.web.ServiceCode;
import cn.tedu.ymg.product.mapper.SubscribeMapper;
import cn.tedu.ymg.product.mapper.UserMapper;
import cn.tedu.ymg.product.pojo.entity.Subscribe;
import cn.tedu.ymg.product.pojo.param.SubscribeAddNewParam;
import cn.tedu.ymg.product.pojo.param.SubscribeUpdateInfoParam;
import cn.tedu.ymg.product.pojo.vo.SubscribeListItemVO;
import cn.tedu.ymg.product.pojo.vo.SubscribeStandardVO;
import cn.tedu.ymg.product.pojo.vo.UserLoginInfoVO;
import cn.tedu.ymg.product.pojo.vo.UserStandardVO;
import cn.tedu.ymg.product.service.ISubscribeService;
import cn.tedu.ymg.product.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class SubscribeServiceImpl implements ISubscribeService {

    @Autowired
    private SubscribeMapper subscribeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private IdUtil idUtil;

    /**
     *  orderNumber(预约编号)，需要根据id，用户id，预约名称进行绑定编号
     * @param subscribeAddNewParam
     */

    @Override
    public void addNew(SubscribeAddNewParam subscribeAddNewParam) {
        log.debug("开始处理【添加预约的业务】，参数:{}",subscribeAddNewParam);
        //检查预约名称是否被占用，如果被占用，则抛出异常
        QueryWrapper<Subscribe> queryWrapper = new QueryWrapper<>();
        //name=参数中的预约名称
        queryWrapper.eq("phone",subscribeAddNewParam.getPhone());
        int countByName = subscribeMapper.selectCount(queryWrapper);
        log.debug("根据示例名称统计匹配的预约数量，结果：{}", countByName);
        if (countByName>0){
            String message = "添加预约失败，预约手机号被占用";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //将预约数据写入到数据库中
        Long userId = userMapper.idByUsername(subscribeAddNewParam.getUsername());
        Subscribe subscribe = new Subscribe();
        BeanUtils.copyProperties(subscribeAddNewParam, subscribe);
        subscribe.setUserId(userId);

        //判断用户是否存在
        UserStandardVO su = userMapper.getStandardById(userId);
        if (su == null){
            String message = "新增订单失败，用户不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        //获取Order ID
        Long orderId = idUtil.generateOrderId();
       //根据用户id和套餐名称生成订单编号
        UUID uuid = UUID.randomUUID();
        String orderNum = userId + "_" + subscribeAddNewParam.getName() + "_" + uuid.toString();

       //将预约数据写入到数据库中

        subscribe.setOrderNumber(orderNum);


        int rows = subscribeMapper.insert(subscribe);
        if (rows !=1){
            String message = "添加预约失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的预约数据写入到数据库，完成！");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除预约】的业务，参数：{}", id);
        Subscribe subscribe = subscribeMapper.selectById(id);
        if (subscribe ==null){
            String message = "删除预约失败，Id不存在";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }

        int rows = subscribeMapper.deleteById(id);
        if (rows!=1){
            String message = "删除预约失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("从数据库删除预约，完成！");
    }

    @Override
    public void updateInfoById(Long id, SubscribeUpdateInfoParam subscribeUpdateInfoParam) {
        log.debug("开始处理【修改预约详情】的业务，ID:{},新数据：{}", id, subscribeUpdateInfoParam);

        //检查预约是否存在，如果不存在，则抛出异常
        QueryWrapper<Subscribe> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = subscribeMapper.selectCount(queryWrapper);
        log.debug("根据示例ID统计匹配的预约数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改预约详情失败，预约数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND, message);
        }

        //执行修改
        Subscribe subscribe = new Subscribe();
        BeanUtils.copyProperties(subscribeUpdateInfoParam, subscribe);
        subscribe.setId(id);
        int rows = subscribeMapper.updateById(subscribe);
        if (rows!=1){
            String message = "修改预约失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("从数据库修改预约，完成！");
    }

    @Override
    public SubscribeStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询预约详情】的业务，参数：{}", id);
        //AlbumStandardVO queryResult = albumMapper.getStandardById(id);//将查询到的结果返回

        SubscribeStandardVO queryResult = subscribeMapper.getStandardById(id);
        if (queryResult==null){
            String message = "查询预约失败，预约数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        return queryResult;
    }

    @Override
    public PageData<SubscribeListItemVO> list(Integer pageNum) {
        Integer pageSize = 5;
        return list(pageNum,pageSize);
    }

    @Override
    public PageData<SubscribeListItemVO> list(Integer pageNum, Integer pageSize) {
        log.debug("开始处理【查询预约列表】的业务，页码：{}，每页记录数：{}", pageNum, pageSize);
        PageHelper.startPage(pageNum,pageSize);
        List<SubscribeListItemVO> list =  subscribeMapper.list();
        PageInfo<SubscribeListItemVO> pageInfo = new PageInfo<>(list);
        PageData<SubscribeListItemVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        return pageData;
    }
}
